package com.tengju.bff.interfaces.covercharge.service.bestsign.util;

import com.alibaba.fastjson.JSONObject;
import com.tengju.bff.interfaces.covercharge.entity.dto.HttpClientResponse;
import com.tengju.bff.interfaces.covercharge.util.HttpClientManager;
import org.apache.http.Header;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * @author shiliang
 * @date 2020/3/23 17:04
 * @description
 */
public class HttpClientUtils {

    /**
     * 响应转换
     */
    private static final HttpResponseHandler COMMON_HANDLER = new HttpResponseHandler();

    public static HttpClientResponse postJson(String url, String content) {
        return postJson(url, content, Collections.emptyList());
    }

    public static HttpClientResponse postJson(String url, String content, List<Header> headers) {
        HttpPost httpPost = new HttpPost(url);
        headers.forEach(httpPost::addHeader);
        httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
        try {
            return HttpClientManager.getHttpClient().execute(httpPost, COMMON_HANDLER);
        } catch (IOException e) {
            //MsgSendUtil.sendUnknownMsg("通讯失败,请检测是否网络正常【" + url + "】", null, e);
            return null;
        }
    }

    public static HttpClientResponse sendHttpGet(String url) {
        return sendHttpGet(url, Collections.emptyList());
    }

    public static HttpClientResponse sendHttpGet(String url, List<Header> headers) {
        HttpGet httpGet = new HttpGet(url);
        headers.forEach(httpGet::addHeader);
        try {
            return HttpClientManager.getHttpClient().execute(httpGet, COMMON_HANDLER);
        } catch (IOException e) {
            //MsgSendUtil.sendUnknownMsg("通讯失败,请检测是否网络正常【" + url + "】", null, e);
            return null;
        }
    }

    /**
     * @param content 响应内容
     * @return 结果转换
     */
    public static JSONObject responseConvert(String content) {
        return JSONObject.parseObject(content);
    }
}
